<script setup>
import request from '@/utils/request';
import { ref, onMounted } from 'vue';
import { filemakerctrl } from 'js-pageoffice';

const titleText = ref('');
const companies = [
  { id: 1, name: '微软（中国）有限公司' },
  { id: 2, name: 'IBM（中国）服务有限公司' },
  { id: 3, name: '亚马逊贸易有限公司' },
  { id: 4, name: '脸书科技有限公司' },
  { id: 5, name: '谷歌网络有限公司' },
  { id: 6, name: '英伟达技术有限公司' },
  { id: 7, name: '台积电科技有限责任公司' },
  { id: 8, name: '沃尔玛股份有限公司' },
];
const selectedCompanies = ref([]);
const isButtonDisabled = ref(false);
const progressBar1Width = ref('0%');
const progressBar1Text = ref('0%');
const progressBar2Width = ref('0%');
const progressBar2Text = ref('0/0');
const errorMsg = ref('');

onMounted(async () => {
  try {
    const response = await request({
      url: '/index',
      method: 'get',
    });
    titleText.value = response;
  } catch (error) {
    console.error('Failed to fetch title:', error);
  }
})

function ConvertFiles() {
  if (selectedCompanies.value.length === 0) {
    alert("请至少选择一个公司");
    return;
  }
  isButtonDisabled.value = true;//禁用按钮,防止重复点击
  ConvertFile(selectedCompanies.value, 0);
}

function ConvertFile(idArr, index) {
  // 设置用于保存文件的服务器端controller地址,该地址需从"/"开始，指向服务器端根目录
  /** 如果想要给SaveFilePage传递多个参数，建议使用new URLSearchParams方式，例如：
* let saveFileUrl = "/FileMaker/save";
* let paramValue = new URLSearchParams({id:1,name:"张三"});
* filemakerctrl.SaveFilePage = `${saveFileUrl}?${paramValue.toString()}`;
*/
  filemakerctrl.SaveFilePage = "/FileMaker/save?id=" + idArr[index];
  filemakerctrl.CallFileMaker({
    // url：指向服务器端FileMakerCtrl打开文件的controller地址，该地址需从"/"开始，指向服务器端根目录  
    url: "/FileMaker/FileMaker?id=" + idArr[index],
    success: (res) => {//res：获取服务器端fs.setCustomSaveResult设置的保存结果
      console.log(res);
      console.log("completed successfully.");
      setProgress1(100);
      index++;
      setProgress2(index, idArr.length);
      if (index < idArr.length) {
        ConvertFile(idArr, index);
      }else {
        isButtonDisabled.value = false;//所有文件转换完毕后启用按钮
      }
    },
    progress: (pos) => {
      console.log("running " + pos + "%");
      setProgress1(pos);
    },
    error: (msg) => {
      errorMsg.value = `发生错误:`+msg;
      console.log("error occurred: " + msg);
      isButtonDisabled.value = false;//发生错误后启用按钮
    },
  });
}
function setProgress1(percent) {
  progressBar1Width.value = percent + "%";
  progressBar1Text.value = percent + "%";
}

function setProgress2(index, count) {
  progressBar2Width.value = Math.round((index / count) * 100) + "%";
  progressBar2Text.value = `${index}/${count}`;
}
</script>

<template>
  <div class="Word">
    <div style="text-align: center">
      <h3>演示：填充数据到模板中批量生成word文件</h3>
      <div style="width: 600px; margin: 0 auto; font-size: 14px">
        <p style="text-align: left">
          演示内容：<br />
          &nbsp;&nbsp;&nbsp;&nbsp;本示例演示了批量生成荣誉证书的效果。选择需要生成荣誉证书的公司，然后点击“批量生成Word文件”按钮，就可以把各个公司名动态填充到荣誉证书模板“template.doc”中，为每个公司生成一份荣誉证书文件。
        </p>
        <p style="text-align: left">
          操作说明：<br />
          1. 勾选下面的公司名称；<br />
          2. 点击“批量生成Word文件”按钮；<br />
          3. 生成完毕后，即可在“FileMaker/doc”目录下看到批量生成的Word文件。<br />
        </p>
      </div>

      <hr />
      <ul class="company-list">
        <li v-for="(company, index) in companies" :key="company.id">
          <label>
            {{ index + 1 }}
            <input v-model="selectedCompanies" :value="company.id" type="checkbox" />
            {{ company.name }}
          </label>
        </li>
      </ul>
      <input id="Button1" type="button" value="批量生成Word文件" @click="ConvertFiles" :disabled="isButtonDisabled" /><br />
      <div id="progressDiv">
        单文件进度：
        <div class="progressBarContainer">
          <div :style="{ width: progressBar1Width, height: '20px', backgroundColor: '#1a73e8', borderRadius: '5px', textAlign: 'center', lineHeight: '20px', color: 'white' }">
            {{ progressBar1Text }}
          </div>
        </div>
        整体进度：
        <div class="progressBarContainer">
          <div :style="{ width: progressBar2Width, height: '20px', backgroundColor: '#1a73e8', borderRadius: '5px', textAlign: 'center', lineHeight: '20px', color: 'white' }">
            {{ progressBar2Text }}
          </div>
        </div>
        <div id="errorMsg">{{ errorMsg }}</div>
      </div>
    </div>
  </div>
</template>
<style scoped>
/* 样式定义 */
h3 {
  display: block;
  font-size: 1.17em;
  margin-block-start: 1em;
  margin-block-end: 1em;
  margin-inline-start: 0px;
  margin-inline-end: 0px;
  font-weight: bold;
}

h2 {
  display: block;
  font-size: 1.5em;
  margin-block-start: 0.83em;
  margin-block-end: 0.83em;
  margin-inline-start: 0px;
  margin-inline-end: 0px;
  font-weight: bold;
}

.progressBarContainer {
  width: 100%;
  background-color: #eee;
  border-radius: 5px;
  padding: 3px;
  box-shadow: 2px 2px 3px 3px #ccc inset;
}

.progressBar {
  height: 20px;
  width: 0%;
  background-color: #1a73e8;
  border-radius: 5px;
  text-align: center;
  line-height: 20px;
  /* 使文字垂直居中 */
  color: white;
}

#progressDiv {
  width: 400px;
  margin: 10px auto;
  text-align: left;
  font-size: 14px;
  border: solid 1px #1a73e8;
  padding: 10px 20px;
  color: #1a73e8;
}

#errorMsg {
  color: red;
}

.company-list {
  list-style-type: none;
  padding: 0;
  margin: 0 auto;
  width: 400px;
}

.company-list li {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.company-list label {
  display: block;
  font-weight: bold;
  margin-bottom: 5px;
}

.company-list input[type="checkbox"] {
  margin-right: 5px;
}
</style>